var H_TOUFANG = "0";
var H_GROW = "1";
var H_PRODUCT = "2";
var H_DONE = "3";

var H_TOUFANG_DESC = "投放阶段";
var H_GROW_DESC = "生长阶段";
var H_PRODUCT_DESC = "收成阶段";
var H_DONE_DESC = "完成阶段";


layui.config({});
layui.use(['form', 'admin', 'ax', 'jquery', 'steps', 'laydate', 'formSelects'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var laydate = layui.laydate;
    var formSelects = layui.formSelects;
    var resultData;
    var status = H_TOUFANG;

    //data
    var materialList = [];
    var productList = [];
    var taskActionList = [];
    //select
    var selectFarmId;
    var selectPoodId;
    var selectMaterials = [];
    var selectProducts = [];
    var selectWorker;
    var selectReviewWorker;
    // var selectClientId;

    //任务
    var selectDayMaterials = [];
    var selectWeekMaterials = [];
    var selectMouthMaterials = [];

    var selectDayOthers = [];
    var selectWeekOthers = [];
    var selectMouthOthers = [];

    window.delInput = delInput;

    //step
    $("#step_demo").step();

    //获取详情信息，填充表单
    if (!Feng.isUndefined(Feng.getUrlParam("planId"))) {
        var ajax = new $ax(Feng.ctxPath + "/api/plan/detail?planId=" + Feng.getUrlParam("planId"));
        result = ajax.start();
        form.val('planForm', result.data);
        resultData = result.data;

        // 反选
        status = resultData.status + '';
        selectFarmId = resultData.farmId;
        selectPoodId = resultData.poodId;
        selectWorker = resultData.worker;
        // selectClientId = resultData.clientId;
        selectReviewWorker = resultData.reviewWorker;
        if (!Feng.isUndefined(resultData.materielList)) {
            var materielListData = JSON.parse(resultData.materielList);
            selectMaterials = materielListData;
        }

        //计划产品[投放|生长]
        //实际产品[收成|完成]
        if (status === H_GROW) {
            if (!Feng.isUndefined(resultData.planProductList)) {
                //产品验收就改
                selectProducts = JSON.parse(resultData.planProductList);
            }
        } else {
            if (!Feng.isUndefined(resultData.productList)) {
                //产品验收就改
                selectProducts = JSON.parse(resultData.productList);
            }
        }

        //反选任务
        if (!Feng.isUndefined(resultData.selectDayMaterials)) {
            selectDayMaterials = JSON.parse(resultData.selectDayMaterials);
        }
        if (!Feng.isUndefined(resultData.selectWeekMaterials)) {
            selectWeekMaterials = JSON.parse(resultData.selectWeekMaterials);
        }
        if (!Feng.isUndefined(resultData.selectMouthMaterials)) {
            selectMouthMaterials = JSON.parse(resultData.selectMouthMaterials);
        }
        if (!Feng.isUndefined(resultData.selectDayOthers)) {
            selectDayOthers = JSON.parse(resultData.selectDayOthers);
        }
        if (!Feng.isUndefined(resultData.selectWeekOthers)) {
            selectWeekOthers = JSON.parse(resultData.selectWeekOthers);
        }
        if (!Feng.isUndefined(resultData.selectMouthOthers)) {
            selectMouthOthers = JSON.parse(resultData.selectMouthOthers);
        }


    }

    loadResultData();

    //加载信息
    function loadResultData() {

        // 进度
        loadStep();

        // UI控制
        loadUIControl();

        // 动作
        loadButtons();

        // 养殖场
        loadFarmList();

        // 物料
        loadMaterialList();

        // 目标产品
        loadProductList();

        // 人员
        loadWorkerList();

        // 审核人员
        loadReviewWorkerList();


        //任务
        loadPlanTask();


    }

    //加载进度

    function loadStep() {
        if (!Feng.isUndefined(resultData)) {
            status = resultData.status + '';
        }
        // step
        $("#step0").removeClass("step-current");
        $("#step" + status).addClass("step-current");
    }

    // 控件控制
    function loadUIControl() {
        if (!Feng.isUndefined(resultData)) {
            status = resultData.status + '';
        }
        //投放阶段
        if (status === H_TOUFANG) {

            $("#harvestTimeForm").addClass("layui-not-events");
            $("#inspectionTimeForm").addClass("layui-not-events");
            $("#product_tip").html("(计划)");
            $("#statusTip").html(H_TOUFANG_DESC + "【原料跟产品选择后不能更改】");
            $("#comfireButton").html("完成投放");
            $("#saveButton").addClass("hide");
        }
        //生长阶段
        if (status === H_GROW || status === H_PRODUCT) {

            $("#basicForm").addClass("layui-not-events");
            $("#farmForm").addClass("layui-not-events");
            $("#materielForm").addClass("layui-not-events");
            $("#productForm").addClass("layui-not-events");
            $("#releaseTimeForm").addClass("layui-not-events");

            if (status === H_GROW) {
                //质检时间禁用
                $("#inspectionTimeForm").addClass("layui-not-events");
                $("#product_tip").html("(计划)");
                $("#statusTip").html(H_GROW_DESC + "【产品可以更改数量跟重量】");
                $("#comfireButton").html("完成生长");


            } else {
                //产品阶段
                $("#poodForm").addClass("layui-not-events");
                $("#workerForm").addClass("layui-not-events");
                //收成时间禁用
                $("#harvestTimeForm").addClass("layui-not-events");
                $("#statusTip").html(H_PRODUCT_DESC + "【产品可以更改数量跟重量】");
                $("#comfireButton").html("完成收成");


            }
        }
        if (status === H_DONE) {
            $("#planContentForm").addClass("layui-not-events");
            $("#comfireButton").addClass("layui-not-events");
            $("#statusTip").html(H_DONE_DESC + "【不能更改】");
            $("#comfireButton").html("无操作");


        }

    }

    //加载养殖场

    function loadFarmList() {

        $("#farmSelect").html('');
        var ajax = new $ax(Feng.ctxPath + "/api/farm/list", function (data) {
            for (var i = 0; i < data.data.length; i++) {
                var name = data.data[i].title;
                var value = data.data[i].farmId;
                var selected = '';
                if (value === selectFarmId) {
                    selected = 'selected';
                }
                if (i === 0 && Feng.isUndefined(selectFarmId) && value !== selectFarmId) {
                    selectFarmId = value;
                    selected = 'selected';
                }
                // name = value + '-' + name;
                $("#farmSelect").append('<option value="' + value + '"  ' + selected + '>' + name + '</option>');

            }
            if (selectFarmId !== undefined) {
                loadFarmDetail();
                loadSelectedFarm();
            }
        });
        ajax.start();
    }

    form.on('select(farmSelect)', function (data) {
        selectFarmId = data.value;
        loadFarmDetail();
        loadSelectedFarm();
    });


    //加载养殖场详情

    function loadFarmDetail() {

        if (!Feng.isUndefined(selectFarmId)) {
            var url = "/api/farm/detail?farmId=" + selectFarmId;
            var ajax = new $ax(Feng.ctxPath + url, function (result) {
                var data = result.data;
                var name = data.title;
                $("#farmName").val(name);
            }, function (data) {
            });
            ajax.start();
        }
    }

    function loadSelectedFarm() {
        loadPoodList();
    }

    //加载养殖池

    function loadPoodList() {

        if (!Feng.isUndefined(selectFarmId)) {
            $("#poodSelect").html('');
            var ajax = new $ax(Feng.ctxPath + "/api/pood/list?limit=100&farmId=" + selectFarmId, function (data) {

                for (var i = 0; i < data.data.length; i++) {
                    var name = data.data[i].title;
                    var value = data.data[i].poodId;

                    var selected = '';
                    if (value === selectPoodId) {
                        selected = 'selected';
                    }
                    if (i === 0 && Feng.isUndefined(selectPoodId) && value !== selectPoodId) {
                        selectPoodId = value;
                        selected = 'selected';
                    }
                    $("#poodSelect").append('<option value="' + value + '"  ' + selected + '>' + name + '</option>');
                }
                form.render();
                if (selectPoodId !== undefined) {
                    loadPoodDetail();
                }

            });
            ajax.start();
        }

    }

    form.on('select(poodSelect)', function (data) {
        selectPoodId = data.value;
        loadPoodDetail();
    });

    //加载养殖池详情(PH,盐度)

    function loadPoodDetail() {

        if (!Feng.isUndefined(selectPoodId)) {
            var url = "/api/pood/detail?poodId=" + selectPoodId;
            var ajax = new $ax(Feng.ctxPath + url, function (result) {
                var data = result.data;
                var name = data.title;
                var ph = data.ph;
                var salt = data.salt;
                var temperature = data.temperature;
                var nitrate = data.nitrate;
                var ammonia = data.ammonia;

                $("#poodName").val(name);
                $("#poodPH").val(ph);
                $("#poodSalt").val(salt);
                $("#poodTemperature").val(temperature);
                $("#poodNitrate").val(nitrate);
                $("#poodAmmonia").val(ammonia);

                //标题

                $("#title").val("养殖场" + "(" + $("#farmName").val() + ")" + "-" + "投放池" + "(" + name + ")");


            }, function (data) {
            });
            ajax.start();
        }
    }


    //加载物料

    function loadMaterialList() {

        $("#materielSelect").html('');
        var ajax = new $ax(Feng.ctxPath + "/api/materiel/list", function (data) {
            for (var i = 0; i < data.data.length; i++) {
                var name = data.data[i].title;
                var value = data.data[i].materielId;
                var specs = data.data[i].specs;
                var maxNumber = data.data[i].number - data.data[i].unuseNumber;
                var unit = data.data[i].unit;

                var type = data.data[i].type + '';
                var typeDesc = "普通原料";
                if (type === '1') {
                    typeDesc = "饲料";
                } else if (type === '2') {
                    typeDesc = "药物";
                }
                var desc = name + "(" + typeDesc + ")";

                var dict = {
                    "value": value,
                    "name": desc,
                    "specs": specs,
                    "maxNumber": maxNumber,
                    "unit": unit,
                    "typeDesc": typeDesc
                };
                materialList.push(dict);
            }
            mutilMateriels();
            form.render();

        }, function (data) {
        });
        ajax.start();
    }

    function mutilMateriels() {
        if (Feng.isArray(materialList)) {
            formSelects.data('materielSelect', 'local', {
                arr: materialList
            });

            if (Feng.isArray(selectMaterials)) {
                var materialIds = [];
                for (var i = 0; i < selectMaterials.length; i++) {
                    var select = selectMaterials[i];
                    materialIds.push(select.value);
                }
                formSelects.value('materielSelect', materialIds);
                loadMaterielsItemList();
            }
        }

    }

    formSelects.on('materielSelect', function (id, vals, val, isAdd, isDisabled) {
        // alert("选择了: " + val.name);
        selectMaterials = vals;
        loadMaterielsItemList();

    }, true);


    function loadMaterielsItemList() {

        var materielsItemList = $("#materielsItemList");
        materielsItemList.html('');
        for (var i = 0; i < selectMaterials.length; i++) {

            var material = selectMaterials[i];
            var name = material.name;
            var specs = material.specs;
            var unit = material.unit;
            var maxNumber = material.maxNumber;
            var number = material.number;
            var numberName = 'materiel_number_' + i;


            var itemForm = '<div class="layui-col-md12">';
            var nameForm = '<div class="layui-inline layui-col-md4">' +
                '<label class="layui-form-label">物料</label>' +
                '<div class="layui-input-block" style="line-height: 38px">' +
                name +
                '</div>' +
                '</div>';

            var weightForm = '<div class="layui-inline layui-col-md4">' +
                '<label class="layui-form-label">规格(g)</label>' +
                '<div class="layui-input-block" style="line-height: 38px">' +
                specs +
                '</div>' +
                '</div>';

            var numberTip = "数量(" + unit + ')' + "(<=" + maxNumber + ")";
            if (!Feng.isUndefined(resultData)) {
                numberTip = "数量(" + unit + ')';
            }
            var numberForm = '<div class="layui-inline layui-col-md4">' +
                '<label class="layui-form-label">' + numberTip + '</label>' +
                '<div class="layui-input-block">' +
                '<input   id= ' + numberName + ' name=' + numberName + ' value= ' + number + '  type="number"  class="layui-input" />' +
                '</div>' +
                '</div>';

            itemForm += nameForm;
            itemForm += weightForm;
            itemForm += numberForm;
            itemForm += '</div>';
            materielsItemList.append(itemForm);

        }

    }


    //加载目标产品

    function loadProductList() {

        $("#productSelect").html('');
        var ajax = new $ax(Feng.ctxPath + "/api/product/list", function (data) {

            for (var i = 0; i < data.data.length; i++) {
                var name = data.data[i].title;
                var value = data.data[i].productId;
                var unit = data.data[i].unit;
                // var weight = data.data[i].weight;
                var dict = {"value": value, "name": name, "unit": unit, "weight": "0", "number": "0"};
                productList.push(dict);
            }
            mutilProducts();
            form.render();

        }, function (data) {
        });
        ajax.start();
    }


    function mutilProducts() {
        if (Feng.isArray(productList)) {

            formSelects.data('productSelect', 'local', {
                arr: productList
            });
            if (Feng.isArray(selectProducts)) {
                var productIds = [];
                for (var i = 0; i < selectProducts.length; i++) {
                    var select = selectProducts[i];
                    productIds.push(select.value);
                }
                formSelects.value('productSelect', productIds);
                loadProductItemList();
            }
        }

    }

    formSelects.on('productSelect', function (id, vals, val, isAdd, isDisabled) {
        // alert("选择了: " + val.name);
        selectProducts = vals;
        loadProductItemList();

    }, true);

    // formSelects.on('productSelect', function (obj) {
    //
    //     selectProducts = obj.checkedData;
    // });

    function loadProductItemList() {
        $("#productItemList").html('');
        for (var i = 0; i < selectProducts.length; i++) {
            var name = selectProducts[i].name;
            var weight = selectProducts[i].weight;
            var number = selectProducts[i].number;
            var unit = selectProducts[i].unit;

            var weightName = 'product_weight_' + i;
            var numberName = 'product_number_' + i;

            var itemForm = '<div class="layui-col-md12">';
            var nameForm = '<div class="layui-inline layui-col-md3">' +
                '<label class="layui-form-label">产品</label>' +
                '<div class="layui-input-block" style="line-height: 38px">' +
                name +
                '</div>' +
                '</div>';

            var weightForm = '<div class="layui-inline layui-col-md3"><label class="layui-form-label">规格(g)</label>' +
                '<div class="layui-input-block">' +
                '<input id= ' + weightName + ' name=' + weightName + ' value=' + weight + ' type="number"  class="layui-input"/>' +
                '</div>' +
                '</div>';

            var numberTip = "数量(" + unit + ')';
            var numberForm = '<div class="layui-inline layui-col-md3"><label class="layui-form-label">' + numberTip + '</label>' +
                '<div class="layui-input-block">' +
                '<input id= ' + numberName + ' name=' + numberName + ' value=' + number + '  type="number"  class="layui-input"/>' +
                '</div>' +
                '</div>';

            itemForm += nameForm;
            itemForm += weightForm;
            itemForm += numberForm;
            itemForm += '</div>';
            $("#productItemList").append(itemForm);

        }

    }

    //=========== 加载工作人员 ========== //

    function loadWorkerList() {

        $("#workerSelect").html('');
        var ajax = new $ax(Feng.ctxPath + "/mgr/allList", function (data) {
            for (var i = 0; i < data.data.length; i++) {
                var name = data.data[i].name;
                var account = data.data[i].account;
                var value = account + "-" + name;
                var select = '';
                if (value === selectWorker) {
                    select = 'selected';
                }
                if (i === 0 && Feng.isUndefined(selectWorker) && value !== selectWorker) {
                    selectWorker = value;
                    select = 'selected';
                }
                var selected = select;
                $("#workerSelect").append('<option value="' + value + '"  ' + selected + '>' + value + '</option>');
            }
            form.render();

        }, function (data) {
        });
        ajax.start();
    }

    form.on('select(workerSelect)', function (data) {
        selectWorker = data.value;
    });

    function loadReviewWorkerList() {

        $("#reviewWorkerSelect").html('');
        var ajax = new $ax(Feng.ctxPath + "/mgr/allList", function (data) {
            for (var i = 0; i < data.data.length; i++) {
                var name = data.data[i].name;
                var account = data.data[i].account;
                var value = account + "-" + name;
                var select = '';
                if (name === selectReviewWorker) {
                    select = 'selected';
                }
                if (i === 0 && Feng.isUndefined(selectReviewWorker) && value !== selectReviewWorker) {
                    selectReviewWorker = value;
                    select = 'selected';
                }
                var selected = select;
                $("#reviewWorkerSelect").append('<option value="' + value + '"  ' + selected + '>' + value + '</option>');
            }
            form.render();

        }, function (data) {
        });
        ajax.start();
    }

    form.on('select(reviewWorkerSelect)', function (data) {
        selectReviewWorker = data.value;
    });





    //=========== 加载任务 ========== //


    function loadPlanTask() {

        //日任务加载

        if (Feng.isArray(selectDayMaterials)) {
            for (var a = 0; a < selectDayMaterials.length; a++) {
                var materiel = selectDayMaterials[a];
                addDayTaskMaterielItem(a, materiel.name + '', materiel.number);
            }
        }
        if (Feng.isArray(selectDayOthers)) {
            for (var b = 0; b < selectDayOthers.length; b++) {
                var other = selectDayOthers[b];
                addDayTaskOtherItem(b, other);
            }
        }
        //月任务加载

        if (Feng.isArray(selectMouthMaterials)) {
            for (var c = 0; c < selectMouthMaterials.length; c++) {
                var materiel = selectMouthMaterials[c];
                addMouthTaskMaterielItem(c, materiel.name + '', materiel.number);
            }
        }
        if (Feng.isArray(selectMouthOthers)) {
            for (var d = 0; d < selectMouthOthers.length; d++) {
                var other = selectMouthOthers[d];
                addMouthTaskOtherItem(d, other);
            }
        }

        //周任务加载

        if (Feng.isArray(selectWeekMaterials)) {
            for (var e = 0; e < selectWeekMaterials.length; e++) {
                var materiel = selectWeekMaterials[e];
                addWeekTaskMaterielItem(e, materiel.name + '', materiel.number);
            }
        }
        if (Feng.isArray(selectWeekOthers)) {
            for (var f = 0; f < selectWeekOthers.length; f++) {
                var other = selectWeekOthers[f];
                addWeekTaskOtherItem(f, other);
            }
        }
    }

    //每日任务

    function addDayTaskOtherItem(index, value) {

        var i = selectDayOthers.length;
        if (index !== null) {
            i = index;
        }
        if (value === null) {
            value = "";
        }
        var selectClassName = 'other_name_' + i + '_day';

        var itemForm = '<div class="layui-col-md12">';
        var nameForm = '<div class="layui-inline layui-col-md8"><label class="layui-form-label">操作</label>' +
            '<div class="layui-input-block">' +
            '<input id= ' + selectClassName + ' name=' + selectClassName + ' type="text" value="' + value + '" placeholder="填写操作" class="layui-input"/>' +
            '</div>' +
            '</div>';
        var del = ' <div class="layui-inline layui-col-md2"><div><button class="layui-btn layui-btn-sm layui-btn-danger layui-btn-radius"  onclick="delInput(this)" type="button" style="margin-left: 10px">删除</button></div></div>'
        itemForm += nameForm;
        itemForm += del;
        itemForm += '</div>';
        $("#dayTaskOtherItemList").append(itemForm);

        if (selectDayOthers.length < i + 1) {
            selectDayOthers[i] = i;
        }
        form.render();

    }

    function addDayTaskMaterielItem(index, value, number) {
        var i = selectDayMaterials.length;
        if (index !== null) {
            i = index;
        }
        if (number === null) {
            number = 0;
        }
        var selectClassName = 'materiel_name_' + i + '_day';
        var numberClass = 'materiel_number_' + i + '_day';
        var unitClass = 'materiel_unit_' + i + '_day';

        var itemForm = '<div class="layui-col-md12">';
        var nameForm = '<div class="layui-inline layui-col-md4">' +
            '<label class="layui-form-label">物料</label>' +
            '<div class="layui-input-block" style="line-height: 38px">' +
            '<input  type="hidden" class="layui-input"> ' +
            '<select  id=' + selectClassName + ' lay-filter=' + selectClassName + '>' +
            '</select>' +
            '</input>' +
            '</div>' +
            '</div>';

        var numberForm = '<div class="layui-inline layui-col-md4"><label class="layui-form-label">数量(斤)</label>' +
            '<div class="layui-input-block">' +
            '<input id= ' + numberClass + ' name=' + numberClass + ' type="text" value=' + number + ' class="layui-input"/>' +
            '</div>' +
            '</div>';
        var del = ' <div class="layui-inline layui-col-md4"><div><button class="layui-btn layui-btn-sm layui-btn-danger layui-btn-radius"  onclick="delInput(this)" type="button" style="margin-left: 10px">删除</button></div></div>'
        itemForm += nameForm;
        itemForm += numberForm;
        itemForm += del;
        itemForm += '</div>';
        $("#dayTaskMaterielItemList").append(itemForm);

        //重新加载
        reloadDayTaskMaterielItem(selectClassName, i, value);
        form.render();

    }

    function reloadDayTaskMaterielItem(selectClassName, index, selectValue) {

        var selectItem = $("#" + selectClassName);
        $(selectItem).html('');
        if (materialList !== undefined) {
            for (var i = 0; i < materialList.length; i++) {
                var item = materialList[i];
                var desc = item.name + ' 规格:' + item.specs + item.unit;
                var value = item.value + '';

                var selected = '';
                if (selectValue !== null && selectValue === value) {
                    selected = 'selected';
                }
                if (i === 0 && Feng.isUndefined(selectValue) && value !== selectValue) {
                    selected = 'selected';
                    if (selectDayMaterials.length === 0) {
                        selectDayMaterials.push(selectValue);
                    }
                }

                $(selectItem).append('<option value="' + value + '"  ' + selected + '>' + desc + '</option>');
            }
        }
        form.on('select(' + selectClassName + ')', function (data) {
            var materielId = data.value;
            selectDayMaterials[index] = materielId;
        });
    }

    //每周任务

    function addWeekTaskOtherItem(index, value) {

        var i = selectWeekOthers.length;
        if (index !== null) {
            i = index;
        }
        if (value === null) {
            value = "";
        }
        var selectClassName = 'other_name_' + i + '_week';
        var itemForm = '<div class="layui-col-md12">';
        var nameForm = '<div class="layui-inline layui-col-md8"><label class="layui-form-label">操作</label>' +
            '<div class="layui-input-block">' +
            '<input id= ' + selectClassName + ' name=' + selectClassName + ' type="text" placeholder="填写操作" value="' + value + '" class="layui-input"/>' +
            '</div>' +
            '</div>';


        var del = ' <div class="layui-inline layui-col-md2"><div><button class="layui-btn layui-btn-sm layui-btn-danger layui-btn-radius"  onclick="delInput(this)" type="button" style="margin-left: 10px">删除</button></div></div>'
        itemForm += nameForm;
        itemForm += del;
        itemForm += '</div>';
        $("#weekTaskOtherItemList").append(itemForm);
        selectWeekOthers[i] = i;
        form.render();

    }


    function addWeekTaskMaterielItem(index, value, number) {
        var i = selectWeekMaterials.length;
        if (index !== null) {
            i = index;
        }
        if (number === null) {
            number = 0;
        }
        var selectClassName = 'materiel_name_' + i + '_week';
        var numberClass = 'materiel_number_' + i + '_week';

        var itemForm = '<div class="layui-col-md12">';
        var nameForm = '<div class="layui-inline layui-col-md4">' +
            '<label class="layui-form-label">物料</label>' +
            '<div class="layui-input-block" style="line-height: 38px">' +
            '<input  type="hidden" class="layui-input"> ' +
            '<select  id=' + selectClassName + ' lay-filter=' + selectClassName + '>' +
            '</select>' +
            '</input>' +
            '</div>' +
            '</div>';

        var numberForm = '<div class="layui-inline layui-col-md4"><label class="layui-form-label">数量(斤)</label>' +
            '<div class="layui-input-block">' +
            '<input id= ' + numberClass + ' name=' + numberClass + ' type="text" value=' + number + ' class="layui-input"/>' +
            '</div>' +
            '</div>';

        var del = ' <div class="layui-inline layui-col-md2"><div><button class="layui-btn layui-btn-sm layui-btn-danger layui-btn-radius"  onclick="delInput(this)" type="button" style="margin-left: 10px">删除</button></div></div>'
        itemForm += nameForm;
        itemForm += numberForm;
        itemForm += del;
        itemForm += '</div>';

        $("#weekTaskMaterielItemList").append(itemForm);

        //重新加载
        reloadWeekTaskMaterielItem(selectClassName, i, value);
        form.render();

    }

    function reloadWeekTaskMaterielItem(selectClassName, index, selectValue) {

        var selectItem = $("#" + selectClassName);
        $(selectItem).html('');
        for (var i = 0; i < materialList.length; i++) {
            var item = materialList[i];
            var desc = item.name + ' 规格:' + item.specs + item.unit;

            var value = item.value + '';

            var selected = '';
            if (selectValue !== null && selectValue === value) {
                selected = 'selected';
            }
            if (i === 0 && Feng.isUndefined(selectValue) && value !== selectValue) {
                selected = 'selected';
                if (selectWeekMaterials.length === 0) {
                    selectWeekMaterials.push(selectValue);
                }
            }

            $(selectItem).append('<option value="' + value + '"  ' + selected + '>' + desc + '</option>');
        }

        form.on('select(' + selectClassName + ')', function (data) {
            var materielId = data.value;
            selectWeekMaterials[index] = materielId;
        });
    }

    //每月任务

    function addMouthTaskOtherItem(index, value) {

        var i = selectMouthOthers.length;
        if (index !== null) {
            i = index;
        }
        if (value === null) {
            value = "";
        }

        var selectClassName = 'other_name_' + i + '_mouth';
        var itemForm = '<div class="layui-col-md12">';
        var nameForm = '<div class="layui-inline layui-col-md8"><label class="layui-form-label">操作</label>' +
            '<div class="layui-input-block">' +
            '<input id= ' + selectClassName + ' name=' + selectClassName + ' type="text" placeholder="填写操作" value="' + value + '" class="layui-input"/>' +
            '</div>' +
            '</div>';
        var del = ' <div class="layui-inline layui-col-md2"><div><button class="layui-btn layui-btn-sm layui-btn-danger layui-btn-radius"  onclick="delInput(this)" type="button" style="margin-left: 10px">删除</button></div></div>'
        itemForm += nameForm;
        itemForm += del;
        itemForm += '</div>';
        $("#mouthTaskOtherItemList").append(itemForm);
        selectMouthOthers[i] = i;

        form.render();

    }


    function addMouthTaskMaterielItem(index, value, number) {
        var i = selectMouthMaterials.length;
        if (index !== null) {
            i = index;
        }
        if (number === null) {
            number = 0;
        }
        var selectClassName = 'materiel_name_' + i + '_mouth';
        var numberClass = 'materiel_number_' + i + '_mouth';

        var itemForm = "<div>"
        var nameForm = '<div class="layui-inline layui-col-md4">' +
            '<label class="layui-form-label">物料</label>' +
            '<div class="layui-input-block" style="line-height: 38px">' +
            '<input  type="hidden" class="layui-input"> ' +
            '<select  id=' + selectClassName + ' lay-filter=' + selectClassName + '>' +
            '</select>' +
            '</input>' +
            '</div>' +
            '</div>';

        var numberForm = '<div class="layui-inline layui-col-md4"><label class="layui-form-label">数量(斤)</label>' +
            '<div class="layui-input-block">' +
            '<input id= ' + numberClass + ' name=' + numberClass + ' type="text" value=' + number + ' class="layui-input"/>' +
            '</div>' +
            '</div>';

        var del = ' <div class="layui-inline layui-col-md2"><div><button class="layui-btn layui-btn-sm layui-btn-danger layui-btn-radius"  onclick="delInput(this)" type="button" style="margin-left: 10px">删除</button></div></div>'
        itemForm += nameForm;
        itemForm += numberForm;
        itemForm += del;
        itemForm += '</div>';
        $("#mouthTaskMaterielItemList").append(itemForm);
        //重新加载
        reloadMouthTaskMaterielItem(selectClassName, i, value);
        form.render();

    }

    function reloadMouthTaskMaterielItem(selectClassName, index, selectValue) {

        var selectItem = $("#" + selectClassName);
        $(selectItem).html('');
        for (var i = 0; i < materialList.length; i++) {
            var item = materialList[i];
            var desc = item.name + ' 规格:' + item.specs + item.unit;
            var value = item.value + '';

            var selected = '';
            if (selectValue !== null && selectValue === value) {
                selected = 'selected';
            }
            if (i === 0 && Feng.isUndefined(selectValue) && value !== selectValue) {
                selected = 'selected';
                if (selectMouthMaterials.length === 0) {
                    selectMouthMaterials.push(selectValue);
                }
            }

            $(selectItem).append('<option value="' + value + '"  ' + selected + '>' + desc + '</option>');

        }

        form.on('select(' + selectClassName + ')', function (data) {
            var materielId = data.value;
            selectMouthMaterials[index] = materielId;
        });
    }


    //渲染时间选择框
    laydate.render({
        elem: '#releaseStartTime'
    });
    laydate.render({
        elem: '#releaseEndTime'
    });
    laydate.render({
        elem: '#harvestTime'
    });
    laydate.render({
        elem: '#inspectionTime'
    });


    //构造请求体

    function buildRequest(onlySave) {

        parseMaterialList();
        parseProductList();
        parseTask();

        status = H_TOUFANG;
        if (!Feng.isUndefined(resultData)) {
            status = resultData.status + '';
        }

        //投放阶段
        if (status === H_TOUFANG) {

            if ($("#releaseStartTime").val() === '' ||
                $("#releaseEndTime").val() === '') {
                Feng.error("投放开始/结束时间都不能为空");
                return false;
            }

            if ($("#title").val() === '') {
                Feng.error("计划标题不能为空");
                return false;
            }
            if (Feng.isUndefined(selectWorker)) {
                Feng.error("执行人都不能为空");
                return false;
            }

            if (Feng.isUndefined(selectReviewWorker)) {
                Feng.error("审核人都不能为空");
                return false;
            }

            if (Feng.isArray(selectMaterials) === false) {
                Feng.error("原料不能为空");
                return false;
            }
            if (Feng.isArray(selectProducts) === false) {
                Feng.error("产品不能为空");
                return false;
            }


        }
        //生长阶段
        if (onlySave === 0) {
            if (status === H_GROW || status === H_PRODUCT) {


                if (status === H_GROW) {
                    if ($("#harvestTime").val() === '') {
                        Feng.error("收成时间都不能为空");
                        return false;
                    }
                } else {



                    if ($("#inspectionTime").val() === '') {
                        Feng.error("质检时间都不能为空");
                        return false;
                    }
                }
            }
        }


        return true;
    }

    function parseMaterialList() {
        for (var i = 0; i < selectMaterials.length; i++) {
            var materiel = selectMaterials[i];
            var numberClass = "materiel_number_" + i;
            var number = $("#" + numberClass).val();
            if (!Feng.isUndefined(number)) {
                materiel.number = number;
            }
            selectMaterials[i] = materiel;

        }
    }

    function parseProductList() {
        for (var i = 0; i < selectProducts.length; i++) {
            var product = selectProducts[i];
            var numberClass = "product_number_" + i;
            var number = $("#" + numberClass).val();
            if (!Feng.isUndefined(number)) {
                product.number = number;
            }

            var weightClass = "product_weight_" + i;
            var weight = $("#" + weightClass).val();
            if (!Feng.isUndefined(weight)) {
                product.weight = weight;
            }

            selectProducts[i] = product;

        }
    }

    //任务

    function parseTask() {

        var selectDayMaterials_t = [];
        for (var a = 0; a < selectDayMaterials.length; a++) {
            var materiel = {};
            var obj = selectDayMaterials[a];
            var bool = $.isPlainObject(obj);
            if (bool === true) {
                materiel = obj;
            } else {
                materiel.name = obj;
            }

            var numberClass = "materiel_number_" + a + '_day';
            var number = $("#" + numberClass).val();
            if (!Feng.isUndefined(number)) {
                materiel.number = number;
                selectDayMaterials_t.push(materiel)
            }
        }
        selectDayMaterials = selectDayMaterials_t;


        var selectDayOthers_t = [];
        for (var b = 0; b < selectDayOthers.length; b++) {
            var other = "";
            var selectClassName = 'other_name_' + b + '_day';
            var value = $("#" + selectClassName).val();
            if (!Feng.isUndefined(value)) {
                other = value;
                selectDayOthers_t.push(other);

            }
        }
        selectDayOthers = selectDayOthers_t;
        //周
        var selectWeekMaterials_t = [];
        for (var c = 0; c < selectWeekMaterials.length; c++) {
            var materiel = {};
            var obj = selectWeekMaterials[c];
            var bool = $.isPlainObject(obj);
            if (bool === true) {
                materiel = obj;
            } else {
                materiel.name = obj;
            }

            var numberClass = "materiel_number_" + c + '_week';
            var number = $("#" + numberClass).val();
            if (!Feng.isUndefined(number)) {
                materiel.number = number;
                selectWeekMaterials_t.push(materiel);

            }
        }
        selectWeekMaterials = selectWeekMaterials_t;

        var selectWeekOthers_t = [];
        for (var d = 0; d < selectWeekOthers.length; d++) {
            var other = "";
            var selectClassName = 'other_name_' + d + '_week';
            var value = $("#" + selectClassName).val();
            if (!Feng.isUndefined(value)) {
                other = value;
                selectWeekOthers_t.push(other);
            }
        }
        selectWeekOthers = selectWeekOthers_t;

        //月
        var selectMouthMaterials_t = [];
        for (var e = 0; e < selectMouthMaterials.length; e++) {
            var materiel = {};
            var obj = selectMouthMaterials[e];
            var bool = $.isPlainObject(obj);
            if (bool === true) {
                materiel = obj;
            } else {
                materiel.name = obj;
            }

            var numberClass = "materiel_number_" + e + '_mouth';
            var number = $("#" + numberClass).val();
            if (!Feng.isUndefined(number)) {
                materiel.number = number;
                selectMouthMaterials_t.push(materiel);
            }

        }
        selectMouthMaterials = selectMouthMaterials_t;

        var selectMouthOthers_t = [];
        for (var f = 0; f < selectMouthOthers.length; f++) {
            var other = "";
            var selectClassName = 'other_name_' + f + '_mouth';
            var value = $("#" + selectClassName).val();
            if (!Feng.isUndefined(value)) {
                other = value;
                selectMouthOthers_t.push(other);
            }
        }
        selectMouthOthers = selectMouthOthers_t;
    }


    form.on('submit(btnSubmit)', function (data) {

        var onlySave = 0;
        if (data.elem.id === "saveButton") {
            onlySave = 1;
        }

        layer.confirm('是否确定', {
            btn: ['确定', '取消']
        }, function (index) {
            toRequest(data, onlySave);
            layer.close(index);
        }, function () {

        });
    });

    function toRequest(data, onlySave) {

        var result = buildRequest(onlySave);
        if (result === false) {
            return;
        }
        data.field.onlySave = onlySave;
        data.field.worker = selectWorker;
        data.field.reviewWorker = selectReviewWorker;
        // data.field.clientId = selectClientId;
        data.field.materielList = JSON.stringify(selectMaterials);

        //计划任务
        if (Feng.isArray(selectDayMaterials)) {
            data.field.selectDayMaterials = JSON.stringify(selectDayMaterials);
        }
        if (Feng.isArray(selectWeekMaterials)) {
            data.field.selectWeekMaterials = JSON.stringify(selectWeekMaterials);
        }
        if (Feng.isArray(selectMouthMaterials)) {
            data.field.selectMouthMaterials = JSON.stringify(selectMouthMaterials);
        }
        if (Feng.isArray(selectDayOthers)) {
            data.field.selectDayOthers = JSON.stringify(selectDayOthers);
        }
        if (Feng.isArray(selectWeekOthers)) {
            data.field.selectWeekOthers = JSON.stringify(selectWeekOthers);
        }
        if (Feng.isArray(selectMouthOthers)) {
            data.field.selectMouthOthers = JSON.stringify(selectMouthOthers);
        }

        if (status === H_TOUFANG) {
            data.field.planProductList = JSON.stringify(selectProducts);
        } else {
            data.field.productList = JSON.stringify(selectProducts);
        }


        var url = "/api/plan/addItem";
        var add = true;
        if ($.trim(data.field.planId) !== '') {
            url = "/api/plan/editItem";
            add = false;
        }
        $.ajax({
            type: "POST",
            contentType: "application/json;charset=UTF-8",
            url: Feng.ctxPath + url,
            data: JSON.stringify(data.field),
            dataType: 'json',
            success: function (result) {
                if (result.code === 0 || result.code === 200) {
                    Feng.success("提交成功！");
                    window.location.href = Feng.ctxPath + '/api/plan'
                } else {
                    Feng.error("提交失败！")
                }
            },error: function (data) {
                Feng.error(data.responseJSON.message);
            }
        });
    }


    //=========== 点击=============
    // 添加按钮点击事件

    function loadButtons() {
        $('#dayBtnA').click(function () {
            addDayTaskMaterielItem(null, null, null);
        });
        $('#dayBtnB').click(function () {
            addDayTaskOtherItem(null, null);
        });
        $('#weekBtnA').click(function () {
            addWeekTaskMaterielItem(null, null, null);
        });
        $('#weekBtnB').click(function () {
            addWeekTaskOtherItem(null, null);
        });
        $('#mouthBtnA').click(function () {
            addMouthTaskMaterielItem(null, null, null);
        });
        $('#mouthBtnB').click(function () {
            addMouthTaskOtherItem(null, null);
        });
    }

    function delInput(that) {
        layer.confirm('是否删除', {
            btn: ['是', '取消']
        }, function (index) {
            $(that).parent().parent().parent().remove();
            layer.close(index);

        }, function () {

        });
    }

    //按钮
    $("#backupPage").click(function () {
        layer.confirm('是否返回', {
            btn: ['返回', '取消']
        }, function () {
            window.location.href = Feng.ctxPath + '/api/plan'
        }, function () {

        });
    });


});